package com.skycity.auth.authentication;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.skycity.auth.constants.SecurityConstants;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken;
import org.springframework.util.Assert;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Decription 添加通过密码的授权模式
 * 参考： {@link OAuth2ClientCredentialsAuthenticationToken}
 * @Author YingBo.Dai
 * @Date 2024/10/24 21:53
 * @Version 1.0
 */
public class OAuth2PasswordAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
    private final String username;
    private final String password;
    private final Set<String> scope;

    public OAuth2PasswordAuthenticationToken(String username, String password, Authentication clientPrincipal,
                                             @Nullable Map<String, Object> additionalParameters) {
        super(SecurityConstants.PASSWORD, clientPrincipal, additionalParameters);
        Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
        Assert.notNull(additionalParameters, "additionalParameters cannot be null");
        this.username = username;
        this.password = password;
        this.scope = new HashSet<>(StrUtil.split(MapUtil.getStr(additionalParameters,OAuth2ParameterNames.SCOPE,"")," ",true,true));
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public Set<String> getScope() {
        return scope;
    }

    @Override
    public String getName() {
        return this.username;
    }
}
